package com.lut.reservation.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lut.reservation.bean.RoomComment;
import com.lut.reservation.bean.RoomReservation;
import com.lut.reservation.bean.User;
import com.lut.reservation.dao.RoomCommentDao;
import com.lut.reservation.exception.BusinessException;
import com.lut.reservation.service.RoomCommentService;
import com.lut.reservation.service.RoomReservationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author zyt
 */
@Slf4j
@Service
public class RoomCommentServiceImpl extends ServiceImpl<RoomCommentDao, RoomComment> implements RoomCommentService {
  @Autowired
  private HttpSession session;

  @Autowired
  private RoomReservationService reservationService;

  @Override
  public boolean save(RoomComment entity) {
    entity.setState("INIT");
    final Object bean = session.getAttribute("user");
    if (bean != null) {
      User user = (User) bean;
      entity.setUserId(user.getId());
      entity.setUserName(user.getName());
    }
    entity.setTime(new Date());
    reservationService.lambdaUpdate()
        .set(RoomReservation::getState, "FINISH")
        .eq(RoomReservation::getId, entity.getReservationId())
        .update();
    return super.save(entity);
  }

  @Override
  public void updateState(Integer id, String state) {
    check(id, state);
    this.lambdaUpdate()
        .set(RoomComment::getState, state)
        .eq(RoomComment::getId, id)
        .update();
  }

  private void check(Integer id, String finish) {
    final RoomComment comment = getById(id);
    if ("INIT".equals(comment.getState())) {
      if (!("PASS".equals(finish) || "REFUSE".equals(finish))) {
        throw new BusinessException("该评论不需要处理，请刷新后重试！");
      }
    }
  }
}
